package com.unionpay.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import com.unionpay.apk.Apk;
import com.unionpay.apk.ApkReader;
import com.unionpay.apk.ApkTool;
import com.unionpay.tool.Files;
import com.unionpay.tool.Shell;
import com.unionpay.tool.Version;

/**
 * 查找所有版本号最高的应用
 * 
 * @author liuzy
 */
public class FindLastApk {
	/* 当前路径 */
	public static String WORK;
	/* 反编译后得到的信息 */
	public static SortedMap<String, Apk> apks = new TreeMap<String, Apk>();
	/* 最后的结果保存到文件  */
	public static final String RESULT = "FindLastApk_Rsult.txt";
	/* 反编译失败日志  */
	public static final String ERROR = "FindLastApk_Error.txt";
	/* 自动识别最新版本保存文件夹  */
	public static final String LASTAPKS = "LastApks";

	public static void main(String[] args) {
		print("************ APK版本扫描工具 ************");
		print("* java -jar FindLastApk.jar [扫描目录]");
		print("* 默认扫描当前目录");
		print("*************************************");
		if (System.getProperty("os.name").startsWith("Win")) {
			print("本程序只适用于Linux");
			System.exit(0);
		}
		// 0.得到当前路径
		WORK = Shell.execute("pwd");
		print("当前路径:" + WORK);
		// 1.写入searchApk.sh并执行，得到结果文件result.txt
		String path = null;
		if (args != null && args.length > 0)
			path = args[0];
		else
			path = WORK;
		SearchApk.search(path);
		// 2.读result.txt文件处理每个apk
		print("读扫描结果文件...");
		File resultFile = new File(WORK + "/" + SearchApk.RSULT_FILE);
		if (resultFile.exists()) {
			print("开始处理...");
			BufferedReader reader = null;
			String line = null;
			try {
				StringBuffer sb = new StringBuffer();
				reader = new BufferedReader(new FileReader(resultFile));
				int n = 0;
				while ((line = reader.readLine()) != null) {
					print(line);
					if (line.contains("/1.apk"))
						continue;
					File apkFile = new File(line);
					File outDir = new File(WORK + "/" + apkFile.getName().substring(0, apkFile.getName().lastIndexOf(".")));
					Files.deleteDir(outDir);
					try {
						ApkTool apkTool = new ApkTool();
						apkTool.setOutDir(outDir);
						apkTool.setApkFile(apkFile);
						apkTool.decode();
						Apk apk = ApkReader.read(outDir);
						apk.setFilePath(apkFile.getPath());
						apk.setFileTime(apkFile.lastModified());
						apks.put(apk.getPackageName() + n++, apk);
					} catch (Exception e) {
						e.printStackTrace();
						sb.append(line + " " + e.getMessage());
					}
					Files.deleteDir(outDir);
				}
				reader.close();
				if (sb.length() > 0) {
					File error = new File(WORK + "/" + ERROR);
					Files.writeFile(sb.toString(), error);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			print("删除扫描结果文件...");
			resultFile.delete();
		} else {
			print("扫描结果文件未找到.");
		}
		// 3.保存处理结果
		Set<String> packageNames = new HashSet<String>();
		StringBuffer sb = new StringBuffer();
		for (String key : apks.keySet()) {
			Apk apk = apks.get(key);
			packageNames.add(apk.getPackageName());
			sb.append(apk.toString() + "\n");
		}
		File result = new File(WORK + "/" + RESULT);
		Files.writeFile(sb.toString(), result);
		System.gc();
		print("所有应用信息保存在" + RESULT);
		// 4.自动识别版本并拷贝
		System.out.print("自动识别版本号,并将最新版拷贝到LastApk文件夹?(Y/N):");
		Scanner input2 = new Scanner(System.in);
		while (true) {
			String s = input2.next();
			if (s.equals("Y") || s.equals("y")) {
				print("处理中，看到异常请等待...");
				File lastApkDir = new File(WORK + "/" + LASTAPKS);
				if (!lastApkDir.exists())
					lastApkDir.mkdir();
				for (String packageName : packageNames) {
					// 按包名找出所有版本
					List<Apk> apkList = new ArrayList<Apk>();
					for (String key : apks.keySet()) {
						Apk apk = apks.get(key);
						if (apk.getPackageName().equals(packageName)) {
							apkList.add(apk);
						}
					}
					Apk lastApk = null;
					for (Apk apk : apkList) {
						String version = apk.getVersion();
						String lastVersin = null;
						if (lastApk != null) {
							lastVersin = lastApk.getVersion();
							if (version.equals(lastVersin)) {
								if (apk.getFileTime() > lastApk.getFileTime()) {
									lastApk = apk;
								}
							} else {
								int diff = Version.compare(apk.getVersion(), lastApk.getVersion());
								if (diff > 0) {
									lastApk = apk;
								} else if (diff == 0) {
									if (apk.getFileTime() > lastApk.getFileTime()) {
										lastApk = apk;
									}
								}
							}
						} else {
							lastApk = apk;
						}
					}
					// 拷贝到LastApkDir
					if (lastApk != null) {
						String newName = lastApk.getPackageName() + "_" + lastApk.getVersion() + "_" + lastApk.getAppName() + ".apk";
						newName = newName.replaceAll("@", "x");
						File newApk = new File(lastApkDir + "/" + newName);
						Files.copyFile(new File(lastApk.getFilePath()), newApk);
					}
				}
			}
			break;
		}
		input2.close();
		print("完成.");
	}

	public static void print(String msg) {
		System.out.println(msg);
	}

}
